package com.lxd.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.lxd.entity.ClubRequest;
import com.lxd.entity.po.*;
import com.lxd.entity.query.*;
import com.lxd.entity.vo.ClubVO;
import com.lxd.entity.vo.UserInfoVO;
import com.lxd.mappers.*;
import com.lxd.redis.RedisUtil;
import com.lxd.utils.CopyTools;
import org.springframework.stereotype.Service;

import com.lxd.entity.enums.PageSize;
import com.lxd.entity.vo.PaginationResultVO;
import com.lxd.service.ClubService;
import com.lxd.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;


/**
 * 业务接口实现
 */
@Service("clubService")
public class ClubServiceImpl implements ClubService {

    @Resource
    private ClubMapper<Club, ClubQuery> clubMapper;
    @Resource
    private MemberMapper<Member, MemberQuery> memberMapper;
    @Resource
    private UserMapper<User, UserQuery> userMapper;
    @Resource
    private FileMapper<File, FileQuery> fileMapper;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<Club> findListByParam(ClubQuery param) {
        return this.clubMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(ClubQuery param) {
        return this.clubMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<ClubVO> findListByPage(ClubQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<Club> list = this.findListByParam(param);
        List<ClubVO> clubVOS = CopyTools.copyList(list, ClubVO.class);

        MemberQuery memberQuery = new MemberQuery();

        for (ClubVO clubVO : clubVOS) {
            clubVO.setImageUrl(getFilePath(clubVO.getId(), 2));
            //查询成员数量
            memberQuery.setClubId(clubVO.getId());
            clubVO.setTotalMemberCount(memberMapper.selectCount(memberQuery));
            //设置到缓存
            redisUtil.setHash("CLUB", clubVO.getId().toString(), clubVO);
        }
        PaginationResultVO<ClubVO> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), clubVOS);
        return result;
    }
    @Override
    public PaginationResultVO<ClubVO> findListByPage2(ClubQuery param) {
        // 获取总数
        int count = this.clubMapper.findListByPage2Count(param);  // 需要添加这个方法
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);

        // 获取列表数据
        List<ClubVO> list = this.clubMapper.findListByPage2(param);

        // 补充每个社团的成员数量
        for (ClubVO clubVO : list) {
            //被禁用的社团不应该有社长名
            if (clubVO.getStatus() == 0) {
                clubVO.setCreatorName(null);
            }
            MemberQuery memberQuery = new MemberQuery();
            memberQuery.setClubId(clubVO.getId());
            Integer memberCount = memberMapper.selectCount(memberQuery);
            clubVO.setTotalMemberCount(memberCount);
        }

        return new PaginationResultVO<>(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
    }
    private String getFilePath(Long relatedId, Integer relatedType) {
        File file = fileMapper.selectLatestByRelatedId(relatedId, relatedType);
        return file == null ? "" : file.getFilePath();
    }


    /**
     * 新增
     */
    @Override
    public Integer add(ClubRequest clubRequest) {
        Club club = CopyTools.copy(clubRequest, Club.class);
        return this.clubMapper.insert(club);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<Club> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.clubMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<Club> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.clubMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(Club bean, ClubQuery param) {
        StringTools.checkParam(param);
        return this.clubMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(ClubQuery param) {
        StringTools.checkParam(param);
        return this.clubMapper.deleteByParam(param);
    }

    /**
     * 根据Id获取对象
     */
    @Override
    public Club getClubById(Long id) {
        return this.clubMapper.selectById(id);
    }

    /**
     * 根据Id修改
     */
    @Override
    public Integer updateClubById(ClubRequest club, Long id) {
        Club bean = CopyTools.copy(club, Club.class);
        return this.clubMapper.updateById(bean, id);
    }

    /**
     * 根据Id删除
     */
    @Override
    public Integer deleteClubById(Long id) {
        return this.clubMapper.deleteById(id);
    }

    @Override
    public List<Club> getMyClubByUserId(Long userId) {

        MemberQuery memberQuery = new MemberQuery();
        memberQuery.setUserId(userId);
        memberQuery.setRole("社长");
        List<Member> members = memberMapper.selectList(memberQuery);
        List<Club> clubs = new ArrayList<>();
        for (Member member : members) {
            Club club = clubMapper.selectById(member.getClubId());
            clubs.add(club);
        }
        return clubs;

    }

    /**
     * 根据社团ID获取成员信息
     */
    @Override
    public List<UserInfoVO> getMembersByClubId(Long clubId) {
        MemberQuery memberQuery = new MemberQuery();
        memberQuery.setClubId(clubId);
        List<UserInfoVO> users = memberMapper.selectList2(memberQuery);
        return users;
    }

    @Override
    public Integer getTotalCount() {
        Integer count = clubMapper.selectCount(new ClubQuery());
        return count;
    }

    @Override
    @Transactional
    public void toggleStatus(Long clubId, Integer status) {
        Date date = new Date();
        if (status == 1) {  // 禁用操作
            // 查找该社团的社长
            MemberQuery query = new MemberQuery();
            query.setClubId(clubId);
            query.setRole("社长");
            List<Member> presidents = memberMapper.selectList(query);

            // 将社长身份改为普通成员
            for (Member president : presidents) {
                Member updateMember = new Member();
                updateMember.setId(president.getId());
                updateMember.setRole("成员");
                memberMapper.updateById(updateMember, president.getId());
                //todo 通知消息
            }
            //修改社团状态
            Club club = new Club();
            club.setUpdatedAt(date);
            club.setCreatorId(null);
            club.setStatus(0);
            clubMapper.updateById(club, clubId);
        } else {  // 启用操作
            //修改社团状态
            Club club = new Club();
            club.setStatus(1);
            club.setCreatorId(null);
            club.setUpdatedAt(date);
            clubMapper.updateById(club, clubId);
        }
    }

}